package com.example.big_event.service.impl;

import com.example.big_event.mapper.UserMapper;
import com.example.big_event.pojo.Result;
import com.example.big_event.pojo.User;
import com.example.big_event.service.UserService;
import com.example.big_event.utils.Md5Util;
import com.example.big_event.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUserName(String username) {
        User user = userMapper.findByUserName(username);
        return user;
    }

    @Override
    public void register(String username, String password) {
        //密码加密
//        String md5String = Md5Util.getMD5String(password);

        //添加
        userMapper.add(username, password);
    }

    @Override
    public Result login(String username, String password) {
//        根据用户名查询用户
        User loginUser = userMapper.findByUserName(username);
        //判断用户是否存在
        if(loginUser == null){
            return Result.error("用户名错误");
        }

        //根据密码来匹配是否正确
        if(password.equals(loginUser.getPassword())){
            return Result.success("登录成功");
        }

        return Result.error("密码错误");
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public void updateAvatar(String avatarUrl) {

        Map<String, Object> map= ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl, id);
    }

    @Override
    public void updatePwd(String newPwd) {
        Map<String, Object> map= ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updatePwd(newPwd,id);
    }

}
